<template>
  <div class="form-setting-panel">
    <!-- start 标题 -->
    <form-title-setting
      :field="field"
      :setting="setting"
      :disabled="false"
      :show-question-icon="false"
      @input="updateForDom"
      :form-title-max-length="10"
    ></form-title-setting>
    <!-- end 标题 -->

    <!-- start 校验 -->
    <div class="form-setting-group form-setting-item">
      <h4 class="form-item-title">{{$t('common.base.check')}}</h4>
      <div class="form-item-box">
        <!-- 必填 -->
        <form-required-setting :field="field" @input="update"></form-required-setting>
      </div>
    </div>
    <!-- end 校验 -->

    <!-- start 字段权限 -->
    <div class="form-setting-group form-setting-item" v-if="!isServiceProviderFlag && !isEventMode">
      <h4 class="form-item-title">{{$t('common.base.fieldPermissions')}}</h4>
      <div class="form-item-box">
        <!-- 支持高级搜索 -->
        <form-search-setting :field="field" @input="update"></form-search-setting>
      </div>
    </div>
    <!-- end 字段权限 -->

    <!-- start 数据来源 -->
    <div class="form-setting-group form-setting-item">
      <h4 class="form-item-title">{{$t('common.base.dataSources')}}</h4>
      <div class="form-item-box">
        <div class="form-setting-item">
          <el-cascader
            v-model='cascaderValue'
            :props="defaultProps"
            :placeholder="$t('common.placeholder.select')"
            :options="appDataList"
            :show-all-levels="false"
            filterable
            @change="handleChangeNodes"
          >
          </el-cascader>

        </div>
      </div>
    </div>
    <!-- end 展示字段 -->

    <!-- start 展示字段 -->
    <div class="form-setting-group form-setting-item">
      <h4 class="form-item-title">{{$t('common.base.showField')}}</h4>
      <div class="form-item-box">
        <div class="form-setting-item">
          <el-select
            v-model="providerRelatedFields"
            value-key="fieldName"
            multiple
            :multiple-limit="max"
          >
            <el-option
              v-for="item in displayFieldList"
              :key="item.fieldName"
              :label="item.displayName"
              :value="item"
            ></el-option>
          </el-select>
        </div>
      </div>
    </div>
    <!-- end 展示字段 -->

  </div>
</template>

<script>
/* mixin */
import SettingMixin from '@src/component/form/mixin/setting';
import FormSubFormMixin from '@src/component/form/mixin/form.subForm';
import * as FormUtil from '@src/component/form/util'

/* props */
import { settingProps } from '@src/component/form/components/props';
import i18n from '@src/locales'

/** api */
import * as PassApi from '@src/api/PassApi.js';
export default {
  name: 'form-relation-form-setting',
  mixins: [SettingMixin, FormSubFormMixin],
  props: settingProps,
  data() {
    return {
      defaultProps: {
        children: 'menuList',
        label: 'menuName',
        value:'passMenuId'
      },
      // 数据来源，级联选择器的数据。
      appDataList:[],
      // 级联选择器的绑定值
      cascaderValue:[],
      // 展示字段的数据
      displayFieldList:[],
      // 是否是首次加载页面
      initStatus:null
    };
  },
  computed: {
    /** 关联表单所关联系统字段 */
    providerRelatedFields: {
      get() {
        return this.subformFields
      },
      set(value) {
        this.update(value, 'subFormFieldList');
      }
    },
  },
  watch:{
    "field":{
      async handler(newVal){
        try {
          this.initStatus = true
          this.cascaderValue = []
          if(!this.appDataList.length){
            await this.getAppPage()
          }
          this.cascaderValue = newVal?.setting?.cascaderValue || []
          await this.handleChangeNodes()
          // 初始化赋值
          this.providerRelatedFields = this.init()
        } catch (error) {
          throw error
        }
      },
      immediate: true
    }
  },
  methods: {
    async handleChangeNodes(){
      const formTemplateBizId = this.cascaderValue[this.cascaderValue.length - 1] || ''
      this.$set( this.field, 'setting', { ...this.field.setting, cascaderValue:this.cascaderValue })
      try{
        // 获取展示字段数据
        const res = await PassApi.getPaasFieldInfoByQueyApi({formTemplateBizId})
        if(!res.success) return
        let data = (res.result || []).filter(val => val.isFlowSystemField !== 1)
        let fields = data.map(field => {
          return {
            ...field,
            id: null, // 去掉原字段id，由后端生成
            setting: {
              ...(field.setting || {}),
              originalFormType: field.formType // 存储原本的类型
            }
          };
        });
        // 清空之前选中的数据
        if(!this.initStatus){
          this.providerRelatedFields = [] 
        }
        this.initStatus = false
        this.displayFieldList = FormUtil.toFormField(fields);
      } catch (error) {
        throw error
      }
    },
    
    // 获取应用数据
    async getAppPage(){
      try{
        const res = await PassApi.getAppPageApi()
        if(!res.success) return 
        let list = res.data || []
        list = this.changeKeyName(list)
        let obj = {
          // 该 passMenuId 为前端自己写死的一个id，可自己随意定义
          passMenuId:'b1a23309-b34f-4b4b-af45-8337de2493bd',
          menuName:'自定义应用',
          menuList:list
        }
        this.appDataList.push(obj)
      } catch (error){
        throw error
      }
    },
    // 递归处理数据里面的key
    changeKeyName(arrayStr){
      if (arrayStr && arrayStr.length > 0) {
        arrayStr.map(item => {
          item.menuName = item.appName
          delete item.appName
          // 该操作，仅仅是处理数据，因为级联选择需要每层的绑定的值相同，所以特意去处理下。
          if(!item.passMenuId && item.paasAppId){
            item.passMenuId = item.paasAppId
            delete item.paasAppId
          }
          if (item.children?.length > 0) {
            this.changeKeyName(item.children)
          }
        })
      }
      return arrayStr
    },

    // 初始化
    init() {
      let providerRelatedFields = this.providerRelatedFields.filter(item => {
        let index = this.displayFieldList.findIndex(field => item.fieldName === field.fieldName)
        return index > -1
      })

      // 已删除的关联显示字段
      let removeFields = this.providerRelatedFields.filter(field =>
        this.displayFieldList.every(option => option.fieldName != field.fieldName)
      )

      // 存在已删除的关联显示字段则提示
      if (removeFields.length) this.showNotification(removeFields)

      return providerRelatedFields
    },
    showNotification(arr = []) {
      this.$notify({
        type: 'warning',
        title: this.$t('common.form.preview.subRelationForm.title1'),
        duration: 0,
        message: (function(h) {
          let fieldNodes = arr.map((item, index) => {
            return (
              <strong>
                {item.displayName}
                {arr.length - 1 != index && '、'}
              </strong>
            );
          });

          return (
            <div class="form-design-notification">
              <p>{i18n.t('common.form.preview.subRelationForm.des1')}</p>
              <div class="form-design-notification-content">{fieldNodes}</div>
            </div>
          );
        })(this.$createElement)
      });
    },

    updateForDom(event){
      let el = event.target;
      let prop = el.dataset.prop;
      let value = el.value;

      this.update(value, prop);
    },
    update(value, prop, isSetting = false) {
      this.$emit('input', {value, prop, isSetting});
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@src/component/form/components/FormSubForm/FormSubForm.scss';
.form-item-box{
  margin-top: 10px;
}
.el-cascader{
  width: 100%;
  ::v-deep .el-input {
    line-height: 8px !important; 
  }
}

</style>
